package com.example.app.service;

import com.example.app.entity.Conversation;
import com.example.app.entity.Message;
import com.example.app.listener.NewMessageEvent;
import com.example.app.mapper.ConversationMapper;
import com.example.app.mapper.MessageMapper;
import jakarta.annotation.Resource;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.time.Instant;

@Service
public class MessageService {
    @Resource
    private ApplicationEventPublisher eventPublisher;
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private ConversationMapper conversationMapper;

    public Message save(Message message) {
        messageMapper.insertMessages(message);
        Conversation conversation = conversationMapper.getConversationBetween(message.getFromUserId(),
                message.getToUserId());
        if (conversation == null) {
            conversation = new Conversation();
            conversation.setType("PRIVATE");
            conversation.setUser1Id(Math.min(message.getFromUserId(), message.getToUserId()));
            conversation.setUser2Id(Math.max(message.getFromUserId(), message.getToUserId()));
            conversation.setLastMessageId(message.getId());
            conversation.setLastMessageContent(message.getContent());
            conversation.setLastMessageAt(message.getSentAt());
            conversation.setUnreadCount(1);
            conversationMapper.insertConversation(conversation);
        } else {
            // 更新会话
            conversationMapper.updateConversationAfterMessage(
                    conversation.getId(),
                    message.getId(),
                    message.getContent(),
                    message.getSentAt(),
                    message.getToUserId() // 增加 receiver 的未读数
            );
        }
        return message;
    }

    @Resource
    private ConversationService conversationService;

    public Message sendMessage(Long senderId, Long receiverId, String content) {
        Message message = new Message();
        message.setFromUserId(senderId);
        message.setToUserId(receiverId);
        message.setContent(content);
        message.setSentAt(Instant.now());
        message.setDelivered(false);

        // 保存消息
        messageMapper.insertMessages(message);

        // 更新会话（略）

        // 🔥 发布事件
        Long conversationId = conversationService.getConversationId(senderId, receiverId);
        eventPublisher.publishEvent(
                new NewMessageEvent(message, receiverId, conversationId)
        );

        return message;
    }
}
